//
//  SearchViewController
//  DownloadTube
//
//  Created by Carlos on 07/10/14.
//  Copyright (c) 2014 Carlos. All rights reserved.
//

import UIKit
import iAd


class SearchViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, ADBannerViewDelegate {

    let videoFinder:VideoFinderProtocol = YoutubeVideoFinder()
    var searchResult = SearchResult()
    var tappedVideoId:String!
    let numberFormatter = NSNumberFormatter()
    var loading = false
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var clearScreenButton: UIBarButtonItem!
    @IBOutlet weak var iADBanner: ADBannerView!
    
    override func viewDidLoad() {
       
        super.viewDidLoad()
        tableView.estimatedRowHeight = 96.0
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.emptyDataSetSource = self
        tableView.tableFooterView = UIView()
        numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
        configureActionNavigationBar()
        iADBanner.delegate = self
        iADBanner.alpha = 0
     }

    override func didReceiveMemoryWarning() {
      
        super.didReceiveMemoryWarning()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
      
        return searchResult.hasNext() ? searchResult.data.count+1 : searchResult.data.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if(indexPath.item < searchResult.data.count) {
            
            let cellIndentifier: NSString = "SearchCell"
            let cell : SearchCell = tableView.dequeueReusableCellWithIdentifier(cellIndentifier) as SearchCell
        
            cell.videoId = searchResult.data[indexPath.item].id
            cell.title.text = searchResult.data[indexPath.item].title
            cell.author.text = searchResult.data[indexPath.item].author
            cell.length.text = searchResult.data[indexPath.item].length
            cell.views.text = Utils.localizedString("%@ views", arguments: [numberFormatter.stringFromNumber(searchResult.data[indexPath.item].views)!])
            cell.thumbnail!.image = LookAndFeel.style.loadingImage
            
            var thumbnail:UIImage?
            
            Async.background {
        
                let data = NSData(contentsOfURL:self.searchResult.data[indexPath.item].thumbnail)
                
                if(data != nil){
                    
                    thumbnail = UIImage(data: data!)
                }
            
                }.main() {
                
                    if(thumbnail != nil){
                        
                        cell.thumbnail!.image = thumbnail
                    }
            }
            
            return cell
            
        } else {
            
            let cellIndentifier: NSString = "MoreDataSearchCell"
            let cellMoreData : MoreDataSearchCell = tableView.dequeueReusableCellWithIdentifier(cellIndentifier) as MoreDataSearchCell
            
            Async.main{
                    
                cellMoreData.moreDataLabel.text = Utils.localizedString("Load more data")
                cellMoreData.activityIndicator.stopAnimating()
                cellMoreData.activityIndicator.hidden = true
            }
            
            return cellMoreData
         }
    }
    
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    
        searchBar.endEditing(true)
        searchResult = SearchResult(query: searchBar.text)
        tableView.reloadData()
        searchVideos()
    }
    
    func searchVideos(){
       
        if(searchResult.nextQueryToken == nil){
            loading = true
            tableView.reloadEmptyDataSet()
        }
        
        Async.background {
            
            let result = self.videoFinder.search(self.searchResult.query, nextResult: self.searchResult.nextQueryToken)
            
            if(result.isFailure()) {
                
                println("error!!")
                
            } else {
                
                self.searchResult.nextQueryToken = result.success()!.nextQueryToken
                self.searchResult.data += result.success()!.data
                
                Async.main {
                    
                    self.tableView.reloadData()
                }
            }
        
            self.loading = false
       
        }
    
        configureActionNavigationBar()
    }
     
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        
        let selectedIndexPath = sender as NSIndexPath
        let viewController = segue.destinationViewController as YoutubePreviewViewController
        let url = NSURL(string: String(format: "http://youtu.be/%@",  searchResult.data[selectedIndexPath.row].id))
        let request = NSURLRequest(URL: url!)
        viewController.request = request
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if(indexPath.row == searchResult.data.count){
            
            let cellMoreData:MoreDataSearchCell = tableView.cellForRowAtIndexPath(indexPath) as MoreDataSearchCell
            
            Async.main{
            
                cellMoreData.moreDataLabel.text = ""
                cellMoreData.activityIndicator.startAnimating()
                cellMoreData.activityIndicator.hidden = false
                
            }.background(after:0.5){
                
                self.searchVideos()
            }
                
           } else {
            
        
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
          
            Async.background{
            
                let result = self.videoFinder.getStreams(self.searchResult.data[indexPath.item].id)
                
                Async.main{
                
                    UIApplication.sharedApplication().networkActivityIndicatorVisible = false
                }
           
            if(result.isFailure()){
                
                let alert = UIAlertController(title: Utils.localizedString("An error was captured"), message: result.failure()!, preferredStyle: UIAlertControllerStyle.Alert)
                alert.addAction(UIAlertAction(title: Utils.localizedString("Ok"), style: UIAlertActionStyle.Default, handler: nil))
                self.presentViewController(alert, animated: true, completion: nil)
             
            } else {
            
                let actionSheet =  UIAlertController(title: Utils.localizedString("Select video quality"), message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
                for videoStream in result.success()! {
                 
                     if(videoStream.videoQuality.playable){
                        
                        var title = String(format:"%@ - %@", videoStream.videoQuality.desc, videoStream.videoQuality.resolution!)
                         actionSheet.addAction(UIAlertAction(title: title, style: UIAlertActionStyle.Default, handler: { (ACTION :UIAlertAction!)in
                            
                                let video = self.searchResult.data[indexPath.item] as Video
                                DownloadManager.sharedInstance.addVideoStreamToDownload(video, videoStream: videoStream)

                            }))
                        }
                }
                
                actionSheet.addAction(UIAlertAction(title: Utils.localizedString("Cancel"), style: UIAlertActionStyle.Cancel, handler: nil))
                self.presentViewController(actionSheet, animated: true, completion: nil)
            }
         }
             }
    }

    @IBAction func clearScreen(){
        
        searchResult = SearchResult(query: nil)
        searchBar.text = ""
        tableView.setContentOffset(CGPointZero, animated: false)
        tableView.reloadData()
        tableView.reloadEmptyDataSet()
        configureActionNavigationBar()
    }
    
    func tableView(tableView: UITableView!, editActionsForRowAtIndexPath indexPath: NSIndexPath!) -> [AnyObject] {
        
        var previewAction = UITableViewRowAction(style: .Normal, title: "Preview") { (action, indexPath) -> Void in
            tableView.editing = false
            
             self.performSegueWithIdentifier("YoutubePreviewSegue", sender: indexPath)
        
        }
        
        previewAction.backgroundColor = LookAndFeel.style.orangeApple
        
        return [previewAction]
    }
    
    func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    }
    
    
    func titleForEmptyDataSet(scrollView:UIScrollView) -> NSAttributedString {
        
        let message = Utils.localizedString("No videos")
        return NSAttributedString(string: message, attributes: LookAndFeel.style.titleEmptyViewAttributes)
    }
    
    func descriptionForEmptyDataSet(scrollView:UIScrollView) -> NSAttributedString {
        
        let message = Utils.localizedString("There are not videos in this view")
        return NSAttributedString(string: message, attributes: LookAndFeel.style.descriptionEmptyViewAttributes)
    }
    
    func imageForEmptyDataSet(scrollView:UIScrollView) -> UIImage {
        
        return UIImage(named: "search-empty-state.png")!.imageByApplyingAlpha(0.7)
    }
    
    func customViewForEmptyDataSet(scrollView:UIScrollView) -> UIView? {
        
       if(loading) {
            
            var activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
            activityView.startAnimating()
            return activityView
        
        }
        
        return nil
    }
    
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        
        return UIStatusBarStyle.LightContent
    }
    
    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        
        searchBar.showsCancelButton = true
        return true
    }
    
    
    func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
 
        searchBar.showsCancelButton = false
        return true
    }
    
    
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        
        searchBar.endEditing(true)
        configureActionNavigationBar()
    }
    
    func configureActionNavigationBar(){
        
        Async.main {
            
            self.clearScreenButton.enabled = !self.searchBar.text.isEmpty || !self.searchResult.data.isEmpty
        }
    }
    
    func bannerViewDidLoadAd(banner: ADBannerView!){
     
        UIView.animateWithDuration(0.5) {
        
            let iADBannerHeight = self.iADBanner.frame.height
            self.iADBanner.alpha = 1
            self.tableView.contentInset = UIEdgeInsetsMake(0, 0, iADBannerHeight, 0);
        }
    }
    
    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!){
        
        UIView.animateWithDuration(0.5) {
            
            self.iADBanner.alpha = 0
            self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        }
    }
    
    
}

